package mnn;

/*
 This program is written by Ahmed Medhat Ahmed
 Egypt
 Alexandria Universty
 Faculty of Science
 Computer Science
 7-7-2007
 a.medhat.cs@gmail.com
 ama_compsc@yahoo.com
 */

import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.ScrollPane;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.EOFException;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.StreamTokenizer;

import javax.swing.BoxLayout;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.JTextField;

public class Test extends JFrame {

	/**
	 * 
	 */
	private static final long serialVersionUID = -8026302151547370950L;

	public static void main(String[] args)// throws
											// FileNotFoundException,IOException,EOFException
	{
		Test app = new Test();
		app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
	}

	private Container container;
	private JPanel P_top, p1, p2, p3, p4;
	private JPanel p11, p12, p13;

	private JPanel p21, p22;

	private JLabel L_top;
	private JLabel L_loadNN, L_loadim;
	private JTextField TF_loadNN, TF_loadim;

	private JButton B_loadNN, B_loadim;

	private JLabel L_testim, L_img, L_tNN, L_NN;

	private JTextArea output;

	private JButton B_test;

	private ObjectInputStream input;
	private int in, out, hl, hn;
	private double lr, mr;
	private int in_array[];

	private int out_array[][];
	private int Dim[];

	private int Dim4[];

	private double weight[][][];
	private File SName;

	private File imName;
	private StreamTokenizer tokenizer;
	private BufferedReader buffer;

	private FileReader file;
	private ImageP imagep;

	private TestNN tester;

	public Test() {
		super("Neural Networkes System");

		container = getContentPane();
		container.setLayout(new BoxLayout(container, BoxLayout.Y_AXIS));

		P_top = new JPanel();
		P_top.setLayout(new FlowLayout());

		L_top = new JLabel();

		Icon img = new ImageIcon("1.jpg");
		L_top.setIcon(img);

		P_top.add(L_top);

		p1 = new JPanel();
		p1.setLayout(new FlowLayout());

		/******************************/
		p11 = new JPanel();
		p11.setLayout(new BoxLayout(p11, BoxLayout.Y_AXIS));

		L_loadNN = new JLabel("Load Neural Network structuer ");
		L_loadim = new JLabel("Load Test Image               ");

		p11.add(L_loadNN);
		p11.add(L_loadim);

		/******************************/
		p12 = new JPanel();
		p12.setLayout(new BoxLayout(p12, BoxLayout.Y_AXIS));

		TF_loadNN = new JTextField(25);
		TF_loadim = new JTextField(25);

		TF_loadNN.setEditable(false);
		TF_loadim.setEditable(false);

		p12.add(TF_loadNN);
		p12.add(TF_loadim);
		/****************************************/
		p13 = new JPanel();
		p13.setLayout(new BoxLayout(p13, BoxLayout.Y_AXIS));

		B_loadNN = new JButton("Browes");
		B_loadim = new JButton("Browes");
		B_loadim.setEnabled(false);
		B_loadNN.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				openstructuer();
				pack();
				setVisible(true);

			}
		});
		B_loadim.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				openimage();
				setVisible(true);
				pack();

			}
		});

		p13.add(B_loadNN);
		p13.add(B_loadim);
		/****************************************/
		p1.add(p11);
		p1.add(p12);
		p1.add(p13);
		/****************************************/
		p2 = new JPanel();
		p2.setLayout(new FlowLayout());
		/****************************************/
		p21 = new JPanel();
		p21.setLayout(new BoxLayout(p21, BoxLayout.Y_AXIS));

		L_testim = new JLabel("Test Image");
		L_img = new JLabel();

		Icon image1 = new ImageIcon("11.JPG");
		L_img.setIcon(image1);

		p21.add(L_testim);
		p21.add(L_img);

		/***************************************/
		p22 = new JPanel();
		p22.setLayout(new BoxLayout(p22, BoxLayout.Y_AXIS));

		L_tNN = new JLabel("Neural Network Status");

		L_NN = new JLabel();
		Icon image2 = new ImageIcon("images/0.JPG");
		L_NN.setIcon(image2);

		p22.add(L_tNN);
		p22.add(L_NN);

		/********************************************/
		p2.add(p21);
		p2.add(p22);
		/************************************************/
		p3 = new JPanel();
		// p3.setLayout(new FlowLayout());

		output = new JTextArea();
		ScrollPane scrollPane = new ScrollPane();
		scrollPane.setSize(350, 150);
		scrollPane.add(output);

		p3.add(scrollPane, BorderLayout.EAST);

		/****************************************************/
		p4 = new JPanel();
		p4.setLayout(new FlowLayout());

		B_test = new JButton("Test this image");
		B_test.setEnabled(false);
		B_test.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				Icon im = new ImageIcon("images/1.gif");
				L_NN.setIcon(im);

				tester = new TestNN(in, out, hl, hn, lr, mr);
				conv_img();
				setweight();
				get_output();

				output.setText(tester.start(in_array, out_array));
			}
		});

		p4.add(B_test);

		/******************************************/
		container.add(P_top);
		container.add(p1);
		container.add(p2);
		container.add(p3);
		container.add(p4);

		setLocation(150, 50);
		pack();
		setVisible(true);
		setResizable(false);

	}

	void conv_img() {
		imagep = new ImageP();
		in_array = new int[in];
		in_array = imagep.conv_to_data(imName.getAbsolutePath(), in);
	}

	void get_output() {
		out_array = new int[out][out];
		for (int i = 0; i < out; i++)
			for (int j = 0; j < out; j++)
				out_array[i][j] = (i == j ? 1 : 0);
	}

	public double getNextNumber() throws EOFException, IOException {
		while (true) {
			int token = 0;
			token = tokenizer.nextToken();
			if (token == StreamTokenizer.TT_EOF)
				throw (new EOFException());
			if (token == StreamTokenizer.TT_NUMBER)
				return tokenizer.nval;
		}
	}

	private void openimage() {
		JFileChooser fileChooser = new JFileChooser();
		fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
		int result = fileChooser.showOpenDialog(this);
		while (result == JFileChooser.CANCEL_OPTION) {
			JOptionPane
					.showMessageDialog(
							this,
							" You must enter the file which contain a structuer of Neural Network ",
							"Invalid file name", JOptionPane.ERROR_MESSAGE);
			result = fileChooser.showOpenDialog(this);
			// return;
		}
		B_test.setEnabled(true);
		imName = fileChooser.getSelectedFile();

		TF_loadim.setText(imName.getAbsolutePath());

		if (imName == null || imName.getName().equals(""))
			JOptionPane.showMessageDialog(this, "Invalid File Name",
					"Invalid file name", JOptionPane.ERROR_MESSAGE);
		else {
			if (imName.exists()) {
				if (imName.isFile()) {
					Icon imag = new ImageIcon(imName.getAbsolutePath());
					L_img.setIcon(imag);
				}
			}
		}
	}

	private void openstructuer() {
		JFileChooser fileChooser = new JFileChooser();
		fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
		int result = fileChooser.showOpenDialog(this);
		while (result == JFileChooser.CANCEL_OPTION) {
			JOptionPane
					.showMessageDialog(
							this,
							" You must enter the file which contain a structuer of Neural Network ",
							"Invalid file name", JOptionPane.ERROR_MESSAGE);
			result = fileChooser.showOpenDialog(this);
			// return;
		}
		B_loadim.setEnabled(true);
		SName = fileChooser.getSelectedFile();

		TF_loadNN.setText(SName.getAbsolutePath());

		if (SName == null || SName.getName().equals(""))
			JOptionPane.showMessageDialog(this, "Invalid File Name",
					"Invalid file name", JOptionPane.ERROR_MESSAGE);
		else {
			try {
				input = new ObjectInputStream(new FileInputStream(SName));
			} catch (IOException ioException) {
				JOptionPane.showMessageDialog(this, "Invalid File Name",
						"Error in opening file", JOptionPane.ERROR_MESSAGE);
			}
			try {
				if (SName.exists()) {
					if (SName.isFile()) {
						StructuerNN struct = (StructuerNN) input.readObject();

						in = struct.getinput();
						out = struct.getoutput();
						hl = struct.gethl();
						hn = struct.gethn();
						lr = struct.getlr();
						mr = struct.getmr();
					}
				} else {
					JOptionPane
							.showMessageDialog(this, SName + " dosent exist");
				}
			} catch (NumberFormatException formatException) {
				JOptionPane.showMessageDialog(this, "bad ",
						"Invalied  Number Format", JOptionPane.ERROR_MESSAGE);
			} catch (IOException ioException) {
				JOptionPane.showMessageDialog(this, "Invalid File Name",
						"Error in opening file", JOptionPane.ERROR_MESSAGE);
			} catch (ClassNotFoundException E) {
				JOptionPane.showMessageDialog(this, "Class not found",
						"Error in opening file", JOptionPane.ERROR_MESSAGE);
			}
		}
	}

	public void setweight() {
		String filexls;
		filexls = SName.getAbsolutePath() + ".xls";
		File F = new File(filexls);
		if (F.exists()) {
			Dim = new int[3];
			tester.getweightsDim(Dim);
			weight = new double[Dim[0]][Dim[2]][Dim[2]];
			Dim4 = new int[Dim[1]];
			tester.getDim4(Dim4);
			try {
				file = new FileReader(F.getAbsolutePath());
				buffer = new BufferedReader(file);
				tokenizer = new StreamTokenizer(buffer);
				for (int i = 0; i < Dim[0]; i++) {
					for (int j = 0; j < Dim4[i]; j++) { // no of in nodes
						for (int k = 0; k < Dim4[i + 1]; k++) {// out nodes
							weight[i][j][k] = this.getNextNumber();
						}
					}
				}
				buffer.close();
				file.close();
				tokenizer = null;
				buffer = null;
				file = null;
			} catch (FileNotFoundException e) {
				JOptionPane.showMessageDialog(null, "error");
			} catch (IOException ee) {
				JOptionPane.showMessageDialog(null, "error");
			}
			tester.setwaites(weight);
		}
	}

}